/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import modelo.Diploma;
import modelo.SituacaoDoDiploma;
import java.util.ArrayList;
import java.util.List;
import modelo.SituacaoDiploma;
import modelo.Telefone;
import modelo.TelefoneDiploma;

/**
 *
 * @author Dirac
 */
public class DiplomaJpaController {

    public DiplomaJpaController() {
        emf = Persistence.createEntityManagerFactory("ArquivoPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Diploma diploma) {
        if (diploma.getSituacaoDoDiplomas() == null) {
            diploma.setSituacaoDoDiplomas(new ArrayList<SituacaoDoDiploma>());
        }
        if (diploma.getTelefoneDiplomas() == null) {
            diploma.setTelefoneDiplomas(new ArrayList<TelefoneDiploma>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
//            List<SituacaoDoDiploma> attachedSituacaoDoDiplomas = new ArrayList<SituacaoDoDiploma>();
//            for (SituacaoDoDiploma situacaoDoDiplomasSituacaoDoDiplomaToAttach : diploma.getSituacaoDoDiplomas()) {
//                situacaoDoDiplomasSituacaoDoDiplomaToAttach = em.getReference(situacaoDoDiplomasSituacaoDoDiplomaToAttach.getClass(), situacaoDoDiplomasSituacaoDoDiplomaToAttach.getId());
//                attachedSituacaoDoDiplomas.add(situacaoDoDiplomasSituacaoDoDiplomaToAttach);
//            }
//            diploma.setSituacaoDoDiplomas(attachedSituacaoDoDiplomas);
//            List<TelefoneDiploma> attachedTelefoneDiplomas = new ArrayList<TelefoneDiploma>();
//            for (TelefoneDiploma telefoneDiplomasTelefoneDiplomaToAttach : diploma.getTelefoneDiplomas()) {
//                telefoneDiplomasTelefoneDiplomaToAttach = em.getReference(telefoneDiplomasTelefoneDiplomaToAttach.getClass(), telefoneDiplomasTelefoneDiplomaToAttach.getId());
//                attachedTelefoneDiplomas.add(telefoneDiplomasTelefoneDiplomaToAttach);
//            }
//            diploma.setTelefoneDiplomas(attachedTelefoneDiplomas);
            em.persist(diploma);
            for(TelefoneDiploma telefoneDiploma:diploma.getTelefoneDiplomas()){
                em.persist(telefoneDiploma.getTelefone());
                em.persist(telefoneDiploma);
            }
//            for (SituacaoDoDiploma situacaoDoDiplomasSituacaoDoDiploma : diploma.getSituacaoDoDiplomas()) {
//                Diploma oldDiplomaOfSituacaoDoDiplomasSituacaoDoDiploma = situacaoDoDiplomasSituacaoDoDiploma.getDiploma();
//                situacaoDoDiplomasSituacaoDoDiploma.setDiploma(diploma);
//                situacaoDoDiplomasSituacaoDoDiploma = em.merge(situacaoDoDiplomasSituacaoDoDiploma);
//                if (oldDiplomaOfSituacaoDoDiplomasSituacaoDoDiploma != null) {
//                    oldDiplomaOfSituacaoDoDiplomasSituacaoDoDiploma.getSituacaoDoDiplomas().remove(situacaoDoDiplomasSituacaoDoDiploma);
//                    oldDiplomaOfSituacaoDoDiplomasSituacaoDoDiploma = em.merge(oldDiplomaOfSituacaoDoDiplomasSituacaoDoDiploma);
//                }
//            }
//            for (TelefoneDiploma telefoneDiplomasTelefoneDiploma : diploma.getTelefoneDiplomas()) {
//                Diploma oldDiplomaOfTelefoneDiplomasTelefoneDiploma = telefoneDiplomasTelefoneDiploma.getDiploma();
//                telefoneDiplomasTelefoneDiploma.setDiploma(diploma);
//                telefoneDiplomasTelefoneDiploma = em.merge(telefoneDiplomasTelefoneDiploma);
//                if (oldDiplomaOfTelefoneDiplomasTelefoneDiploma != null) {
//                    oldDiplomaOfTelefoneDiplomasTelefoneDiploma.getTelefoneDiplomas().remove(telefoneDiplomasTelefoneDiploma);
//                    oldDiplomaOfTelefoneDiplomasTelefoneDiploma = em.merge(oldDiplomaOfTelefoneDiplomasTelefoneDiploma);
//                }
//            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Diploma diploma) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
//            Diploma persistentDiploma = em.find(Diploma.class, diploma.getId());
//            List<SituacaoDoDiploma> situacaoDoDiplomasOld = persistentDiploma.getSituacaoDoDiplomas();
//            List<SituacaoDoDiploma> situacaoDoDiplomasNew = diploma.getSituacaoDoDiplomas();
//            List<TelefoneDiploma> telefoneDiplomasOld = persistentDiploma.getTelefoneDiplomas();
//            List<TelefoneDiploma> telefoneDiplomasNew = diploma.getTelefoneDiplomas();
//            List<String> illegalOrphanMessages = null;
//            for (SituacaoDoDiploma situacaoDoDiplomasOldSituacaoDoDiploma : situacaoDoDiplomasOld) {
//                if (!situacaoDoDiplomasNew.contains(situacaoDoDiplomasOldSituacaoDoDiploma)) {
//                    if (illegalOrphanMessages == null) {
//                        illegalOrphanMessages = new ArrayList<String>();
//                    }
//                    illegalOrphanMessages.add("You must retain SituacaoDoDiploma " + situacaoDoDiplomasOldSituacaoDoDiploma + " since its diploma field is not nullable.");
//                }
//            }
//            for (TelefoneDiploma telefoneDiplomasOldTelefoneDiploma : telefoneDiplomasOld) {
//                if (!telefoneDiplomasNew.contains(telefoneDiplomasOldTelefoneDiploma)) {
//                    if (illegalOrphanMessages == null) {
//                        illegalOrphanMessages = new ArrayList<String>();
//                    }
//                    illegalOrphanMessages.add("You must retain TelefoneDiploma " + telefoneDiplomasOldTelefoneDiploma + " since its diploma field is not nullable.");
//                }
//            }
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
//            List<SituacaoDoDiploma> attachedSituacaoDoDiplomasNew = new ArrayList<SituacaoDoDiploma>();
//            for (SituacaoDoDiploma situacaoDoDiplomasNewSituacaoDoDiplomaToAttach : situacaoDoDiplomasNew) {
//                situacaoDoDiplomasNewSituacaoDoDiplomaToAttach = em.getReference(situacaoDoDiplomasNewSituacaoDoDiplomaToAttach.getClass(), situacaoDoDiplomasNewSituacaoDoDiplomaToAttach.getId());
//                attachedSituacaoDoDiplomasNew.add(situacaoDoDiplomasNewSituacaoDoDiplomaToAttach);
//            }
//            situacaoDoDiplomasNew = attachedSituacaoDoDiplomasNew;
//            diploma.setSituacaoDoDiplomas(situacaoDoDiplomasNew);
//            List<TelefoneDiploma> attachedTelefoneDiplomasNew = new ArrayList<TelefoneDiploma>();
//            for (TelefoneDiploma telefoneDiplomasNewTelefoneDiplomaToAttach : telefoneDiplomasNew) {
//                telefoneDiplomasNewTelefoneDiplomaToAttach = em.getReference(telefoneDiplomasNewTelefoneDiplomaToAttach.getClass(), telefoneDiplomasNewTelefoneDiplomaToAttach.getId());
//                attachedTelefoneDiplomasNew.add(telefoneDiplomasNewTelefoneDiplomaToAttach);
//            }
//            telefoneDiplomasNew = attachedTelefoneDiplomasNew;
//            diploma.setTelefoneDiplomas(telefoneDiplomasNew);
            diploma = em.merge(diploma);
//            for (SituacaoDoDiploma situacaoDoDiplomasNewSituacaoDoDiploma : situacaoDoDiplomasNew) {
//                if (!situacaoDoDiplomasOld.contains(situacaoDoDiplomasNewSituacaoDoDiploma)) {
//                    Diploma oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma = situacaoDoDiplomasNewSituacaoDoDiploma.getDiploma();
//                    situacaoDoDiplomasNewSituacaoDoDiploma.setDiploma(diploma);
//                    situacaoDoDiplomasNewSituacaoDoDiploma = em.merge(situacaoDoDiplomasNewSituacaoDoDiploma);
//                    if (oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma != null && !oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma.equals(diploma)) {
//                        oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma.getSituacaoDoDiplomas().remove(situacaoDoDiplomasNewSituacaoDoDiploma);
//                        oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma = em.merge(oldDiplomaOfSituacaoDoDiplomasNewSituacaoDoDiploma);
//                    }
//                }
//            }
//            for (TelefoneDiploma telefoneDiplomasNewTelefoneDiploma : telefoneDiplomasNew) {
//                if (!telefoneDiplomasOld.contains(telefoneDiplomasNewTelefoneDiploma)) {
//                    Diploma oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma = telefoneDiplomasNewTelefoneDiploma.getDiploma();
//                    telefoneDiplomasNewTelefoneDiploma.setDiploma(diploma);
//                    telefoneDiplomasNewTelefoneDiploma = em.merge(telefoneDiplomasNewTelefoneDiploma);
//                    if (oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma != null && !oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma.equals(diploma)) {
//                        oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma.getTelefoneDiplomas().remove(telefoneDiplomasNewTelefoneDiploma);
//                        oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma = em.merge(oldDiplomaOfTelefoneDiplomasNewTelefoneDiploma);
//                    }
//                }
//            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = diploma.getId();
                if (findDiploma(id) == null) {
                    throw new NonexistentEntityException("The diploma with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Diploma diploma;
            try {
                diploma = em.getReference(Diploma.class, id);
                diploma.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The diploma with id " + id + " no longer exists.", enfe);
            }

            List<TelefoneDiploma> telefoneDiplomas = new TelefoneDiplomaJpaController().findToDiploma(diploma);

            if(telefoneDiplomas!= null){
                for(TelefoneDiploma td: telefoneDiplomas){
                   //em.remove(td.getTelefone());
                    System.out.println(td.getId());
                   //em.remove(td);
                }
            }
            em.remove(diploma);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Diploma> findDiplomaEntities() {
        return findDiplomaEntities(true, -1, -1);
    }

    public List<Diploma> findDiplomaEntities(int maxResults, int firstResult) {
        return findDiplomaEntities(false, maxResults, firstResult);
    }

    private List<Diploma> findDiplomaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Diploma as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Diploma findDiploma(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Diploma.class, id);
        } finally {
            em.close();
        }
    }

    public int getDiplomaCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Diploma as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public List<Diploma> search(Diploma diploma) {
        EntityManager em = getEntityManager();
        try {
        List<Diploma> listaAux = new ArrayList<Diploma>();
        List<Diploma> lista = findDiplomaEntities();

        if (diploma.getId() != null && diploma.getId() != 0) {
            lista.clear();
            lista.add(findDiploma(diploma.getId()));
            return lista;
        }

        if (diploma.getAluno() != null && (!diploma.getAluno().equals("")) ) {
            Query query = em.createQuery("SELECT p FROM Diploma p WHERE p.aluno like :aluno ");
            query.setParameter("aluno", "%" + diploma.getAluno() + "%");
            System.out.println(query.toString());
            lista = query.getResultList();
            return lista;
        }



        if (diploma.getSituacaoDiploma() != null && (!diploma.getSituacaoDiploma().equals("")) ) {
            Query query = em.createQuery("SELECT p FROM Diploma p WHERE p.situacao like :situacao ");
            query.setParameter("situacao", diploma.getSituacaoDiploma());
            System.out.println(query.toString());
            lista = query.getResultList();
        }

            return lista;
        } finally {
            em.close();
        }
    }

    public List<Diploma> searchSituacao(SituacaoDiploma situacaoDiploma) {
        EntityManager em = getEntityManager();
        try {
        List<Diploma> lista = findDiplomaEntities();

        if (situacaoDiploma != null && (!situacaoDiploma.equals("")) ) {
            Query query = em.createQuery("SELECT p FROM Diploma p WHERE p.situacaoDiploma = :situacao ");
            query.setParameter("situacao", situacaoDiploma);
            lista = query.getResultList();
        }

            return lista;
        } finally {
            em.close();
        }
    }

}
